package com.example.demo.controller;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/redisson")
public class RedissonController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    RedissonClient redissonClient;

    @GetMapping("/save")
    public String save(){
        stringRedisTemplate.opsForValue().set("key","redisson");
        return "save ok";
    }

    @GetMapping("/get")
    public String get(){

        RLock lock = redissonClient.getLock ( "myLock" );
        String str=null;
        if (lock.tryLock ()){
            System.out.println ("拿到了锁");
            str=stringRedisTemplate.opsForValue().get("key");
        }else{
            System.out.println ("没有拿到锁");
        }
        lock.unlock ();

        return str;
    }

}